# -*- coding: utf-8 -*-
"""
HaaS506 RTU 预警模块
实时监测电流异常并触发报警
"""

import utime
import rtu_config
import rtu_modbus
import rtu_data
import rtu_mqtt

# 预警状态
_warning_enabled = False
_current_warning_value = 80.0
_current_max_time = 5
_warning_start_time = None
_last_check_time = 0
_check_interval = 1  # 每秒检查一次
_is_warning_active = False


def init():
    """初始化预警模块"""
    global _warning_enabled, _current_warning_value, _current_max_time
    
    try:
        # 从配置中读取预警参数
        warning_config = rtu_config.get_config("warning", {})
        _warning_enabled = warning_config.get("current_check", 0) == 1
        _current_max_time = warning_config.get("current_max_time", 5)
        _current_warning_value = float(warning_config.get("current_warning_value", 80))
        
        if _warning_enabled:
            print("[WARNING] Current warning initialized:")
            print("[WARNING] - Warning value: {}A".format(_current_warning_value))
            print("[WARNING] - Max time: {}s".format(_current_max_time))
        else:
            print("[WARNING] Current warning disabled")
        
        return True
        
    except Exception as e:
        print("[WARNING] Init error: {}".format(e))
        return False


def check_current_warning():
    """检查电流是否异常"""
    global _warning_start_time, _last_check_time, _is_warning_active
    
    if not _warning_enabled:
        return False
    
    current_time = utime.time()
    
    # 限制检查频率
    if current_time - _last_check_time < _check_interval:
        return False
    
    _last_check_time = current_time
    
    try:
        # 读取三相电流
        current_data = rtu_modbus.read_three_phase_current()
        if not current_data:
            print("[WARNING] Failed to read three phase current")
            _warning_start_time = None
            return False
        
        # 获取三相电流值
        current_a = current_data.get("current_a", 0.0)
        current_b = current_data.get("current_b", 0.0)
        current_c = current_data.get("current_c", 0.0)
        
        # 检查是否有任意相电流超过阈值
        over_current = False
        over_current_phase = ""
        
        if current_a > _current_warning_value:
            over_current = True
            over_current_phase = "A"
        elif current_b > _current_warning_value:
            over_current = True
            over_current_phase = "B"
        elif current_c > _current_warning_value:
            over_current = True
            over_current_phase = "C"
        
        if over_current:
            # 电流超过阈值
            if _warning_start_time is None:
                # 第一次检测到超限，记录开始时间
                _warning_start_time = current_time
                print("[WARNING] Current over limit detected on phase {}: A={:.2f}, B={:.2f}, C={:.2f}".format(
                    over_current_phase, current_a, current_b, current_c))
            else:
                # 计算持续时间
                duration = current_time - _warning_start_time
                
                if duration >= _current_max_time and not _is_warning_active:
                    # 达到预警条件，触发报警
                    print("[WARNING] Current warning triggered! Phase {} over {}A for {}s".format(
                        over_current_phase, _current_warning_value, duration))
                    
                    _is_warning_active = True
                    
                    # 立即执行数据采集并上传
                    _trigger_warning_action()
                    
                    return True
                else:
                    print("[WARNING] Current over limit for {:.1f}s (phase {})".format(
                        duration, over_current_phase))
        else:
            # 电流恢复正常
            if _warning_start_time is not None:
                print("[WARNING] Current returned to normal: A={:.2f}, B={:.2f}, C={:.2f}".format(
                    current_a, current_b, current_c))
                
            _warning_start_time = None
            _is_warning_active = False
        
        return False
        
    except Exception as e:
        print("[WARNING] Check current warning error: {}".format(e))
        _warning_start_time = None
        return False


def _trigger_warning_action():
    """触发预警动作"""
    try:
        print("[WARNING] Triggering warning action...")
        
        # 立即采集数据（紧急采集，不对齐时间）
        data = rtu_data.collect_data(emergency=True)
        if data:
            print("[WARNING] Emergency data collected")
            
            # 如果MQTT已连接，立即上传
            if rtu_config.g_mqtt_connected:
                if rtu_mqtt.publish_data(data):
                    print("[WARNING] Emergency data uploaded")
                else:
                    print("[WARNING] Emergency data upload failed")
            else:
                print("[WARNING] MQTT not connected, data cached")
        else:
            print("[WARNING] Emergency data collection failed")
            
    except Exception as e:
        print("[WARNING] Trigger warning action error: {}".format(e))


def update_config(config_dict):
    """更新预警配置"""
    global _warning_enabled, _current_warning_value, _current_max_time
    
    try:
        if "current_check" in config_dict:
            _warning_enabled = config_dict["current_check"] == 1
            
        if "current_max_time" in config_dict:
            _current_max_time = int(config_dict["current_max_time"])
            
        if "current_warning_value" in config_dict:
            _current_warning_value = float(config_dict["current_warning_value"])
        
        print("[WARNING] Config updated:")
        print("[WARNING] - Enabled: {}".format(_warning_enabled))
        print("[WARNING] - Warning value: {}A".format(_current_warning_value))
        print("[WARNING] - Max time: {}s".format(_current_max_time))
        
        return True
        
    except Exception as e:
        print("[WARNING] Update config error: {}".format(e))
        return False


def get_warning_status():
    """获取预警状态"""
    return {
        "enabled": _warning_enabled,
        "warning_value": _current_warning_value,
        "max_time": _current_max_time,
        "is_active": _is_warning_active,
        "start_time": _warning_start_time
    }


def test_warning():
    """测试预警功能"""
    print("[WARNING] Testing warning module...")
    
    # 显示当前配置
    status = get_warning_status()
    print("[WARNING] Current status: {}".format(status))
    
    # 测试电流读取
    current_data = rtu_modbus.read_three_phase_current()
    if current_data:
        print("[WARNING] Current data: {}".format(current_data))
    else:
        print("[WARNING] Failed to read current data")
    
    # 测试预警检查
    check_current_warning()
    
    print("[WARNING] Test completed")